from overrides import override
import logging
import typing as T
from fastapi import Depends
import time
from datetime import datetime

from ..EmpsService import EmpsService
from ...mapper.EmpsMapper import EmpsMapper
from ...dto.PageParam import PageParam
from ...dto.EmpPageData import EmpPageData
from ...dto.Emp import Emp
from ...utils.JwtUtils import JwtUtils
from ...init import ENV
from ...dto.OperateLog import OperateLog
from ...utils import SplitString2Number


class _EmpServiceImp(EmpsService):

    def __call__(self, empsMapper: EmpsMapper):
        self.empsMapper = empsMapper
        return self

    @override
    async def list(self, pageParam: PageParam):
        pageParam.page = (pageParam.page - 1) * pageParam.pageSize
        rows = await self.empsMapper.list(pageParam)
        total = await self.empsMapper.count(pageParam)
        rows = list(map(lambda x: Emp(**x.model_dump(exclude={"password"})), rows))
        logging.info(f"EmpServiceImp.list() total={total}, result: {rows}")
        result = EmpPageData(rows=rows, total=total)
        return result

    @override
    async def delete(self, ids: str):
        await self.empsMapper.delete(SplitString2Number.split_string_to_number(ids))

    @override
    async def save(self, emp: Emp):
        emp.updateTime = datetime.now()
        await self.empsMapper.save(emp)

    @override
    async def getById(self, id: int):
        result = await self.empsMapper.getById(id)
        logging.info(f"EmpServiceImp.getById() result: {result}")
        return result

    @override
    async def update(self, emp: Emp):
        await self.empsMapper.update(emp)

    @override
    async def login(self, username: str, password: str):
        result = await self.empsMapper.login(username, password)
        logging.info(f"EmpServiceImp.loggin() result: {result}")
        if result is None:
            return None
        result = JwtUtils.encode(
            {
                "id": result.id,
                "username": result.username,
                "exp": ENV.JWT_EXP * 1000 + int(time.time()),
            }
        )
        return result


EmpService = T.Annotated[_EmpServiceImp, Depends(_EmpServiceImp())]
